package com.lxw.oa.controller.common;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lxw.oa.controller.io.BaseTo;
import com.lxw.oa.entity.User;
import com.lxw.oa.service.ResourceService;
import com.lxw.oa.util.LogAopIn;
import com.lxw.oa.util.POIWordUtil;
import com.lxw.oa.util.PoiExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@EnableTransactionManagement
@RequestMapping("/resource")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @LogAopIn(moduleName="资源管理-头像管理",option="页面初始化")
    @GetMapping("/userImg")
    public String Log_userImg()
    {
        return "pages/resource/UserImgManager";
    }

    @LogAopIn(moduleName="资源管理-模板管理",option="页面初始化")
    @GetMapping("/modalManager")
    public String Log_modalManager()
    {
        return "pages/resource/ModalManager";
    }

    @LogAopIn(moduleName="资源管理-导出管理",option="页面初始化")
    @GetMapping("/exportManager")
    public String Log_exportManager(ModelMap modelMap)
    {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String  userName = user.getName();
        modelMap.put("userName",userName);
        return "pages/resource/ExportManager";
    }

    @LogAopIn(moduleName="资源管理-模板管理",option="模板上传")
    @RequestMapping("/upLoadModal")
    @ResponseBody
    public BaseTo Log_upLoadModal(@RequestParam("file") MultipartFile file,String nameEnd,String mark,String fileName){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String  userName = user.getName();
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        String uuid=UUID.randomUUID().toString().replace("-", "");
        if(file==null){
            return new BaseTo("上传失败,未接收到文件");
        }
        String uuidFileName=uuid+"."+nameEnd;
        String filePath = "src/main/resources/static/files/";
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath+uuidFileName);
            out.write(file.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseTo("上传失败," + e.getMessage());
        }
        resourceService.addModalMessage(uuidFileName,fileName,nameEnd,mark,userName,dateString);
        return new BaseTo("");
    }

    @LogAopIn(moduleName="资源管理-模板管理",option="模板删除")
    @RequestMapping("/delModal")
    @ResponseBody
    public BaseTo Log_delModal(String fileName){
        try {
            //删除成功后也需要删除该文件夹
            File file=new File("src/main/resources/static/files/"+fileName);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseTo("上传失败," + e.getMessage());
        }
        return new BaseTo("");
    }

    @LogAopIn(moduleName="资源管理-模板管理",option="模板下载")
    @RequestMapping("/download")
    public void  Log_downloadFile(HttpServletResponse response,String fileName,String uFileName) {
        //String OApath=ClassUtils.getDefaultClassLoader().getResource("").getPath();
        File file=new File("src/main/resources/static/files/"+uFileName);
        String fileEnd=uFileName.substring(32);
        if (file.exists() && file.isFile()) {
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 设置文件名
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName+fileEnd, "UTF-8"));
                byte[] buffer = new byte[1024];
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    os.flush();
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else{
        }
    }


    @RequestMapping("/downloadCheck")
    @ResponseBody
    public BaseTo  downloadCheck(String uFileName) {
        File file=new File("src/main/resources/static/files/"+uFileName);
        if (file.exists() && file.isFile()) {
          return new BaseTo("");
        }else{
          return new BaseTo("文件不存在");
        }
    }

    @PostMapping("/dataVeiw")
    @ResponseBody
    public BaseTo  dataVeiw(String message) {
        JSONObject json = JSONObject.parseObject(message);
        JSONArray sqls=JSONArray.parseArray(json.getString("sqls"));
        int sqlslength=sqls.size();
        String [] sqlsColumn=sqls.toArray(new String[sqlslength]);
        Map<String,Object>mapAll=new HashMap<String,Object>();
        for(String sql:sqlsColumn){
            sql = sql.replaceAll("\"", "\'");
            if(sql.toUpperCase().contains("DELETE")||sql.toUpperCase().contains("CREATE")||sql.toUpperCase().contains("INSERT")
                ||sql.toUpperCase().contains("UPDATE")||sql.toUpperCase().contains("TRUNCATE")||sql.toUpperCase().contains("DROP")){
                return new BaseTo("SQL语句有非法关键字(delete，drop等)");
            }
            try {
                List<Map<String,Object>>list1=resourceService.getOneSqlData(sql);
                if(null!=list1&&list1.size()!=0){
                    for(Map<String,Object>map:list1){
                        Set<String>keySet=map.keySet();
                        if(keySet.size()!=2||!keySet.contains("keyValue")||!keySet.contains("Value")){
                            return new BaseTo("SQL语句查询结果格式有误");
                        }else{
                            if(mapAll.containsKey(map.get("keyValue"))){
                                return new BaseTo("SQL语句查询结果keyValue有重复值");
                            }else{
                                mapAll.put(map.get("keyValue").toString(),map.get("Value"));
                            }
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                return new BaseTo("SQL语句执行有误");
            }
        }
        Set<String>keySetAll=mapAll.keySet();
        List<Map<String,String>>listAll=new ArrayList<Map<String,String>>();
        for(String demo:keySetAll){
            Map<String,String>mapMessage=new HashMap<String,String>();
            mapMessage.put("keyValue","${"+demo+"}");
            mapMessage.put("Value",mapAll.get(demo).toString());
            listAll.add(mapMessage);
        }
        return new BaseTo(listAll);
    }

    public Map<String,String> backDataMap(String sql) {
        Map<String,String>mapAll=new HashMap<String,String>();
            sql = sql.replaceAll("\"", "\'");
                List<Map<String,Object>>list1=resourceService.getOneSqlData(sql);
                    for(Map<String,Object>map:list1){
                        Set<String>keySet=map.keySet();
                        mapAll.put("${"+map.get("keyValue")+"}",map.get("Value").toString());
                }
        return mapAll;
    }



    @LogAopIn(moduleName="资源管理-导出管理",option="自定义导出")
    @RequestMapping("/myExport")
    public void  Log_myExport(HttpServletResponse response,String uFileName,String sqls,String fileName) {
        Map map=backDataMap(sqls);
        String fileEnd=uFileName.substring(32);
        String path="src/main/resources/static/files/"+uFileName;
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 设置文件名
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName+fileEnd, "UTF-8"));
            OutputStream os= response.getOutputStream();
            if(".docx".equals(fileEnd)){
               // XWPFDocument hwb=POIWordUtil.replaceWordModelXWPF(map,path,null);
               XWPFDocument hwb=POIWordUtil.replaceWordModel(map,path);
                hwb.write(os);
                os.close();
            }else if(".doc".equals(fileEnd)){


            }else if(".xls".equals(fileEnd)){
                Workbook hwb= PoiExcelUtil.replaceExcelModelHSS(map,path);
                hwb.write(os);
                os.close();
            }else{
                Workbook hwb= PoiExcelUtil.replaceExcelModelXSS(map,path);
                hwb.write(os);
                os.close();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
